'use strict'
$(function () {
    query()
    let id = location.search.split('?')[1]
    console.log(id);
   
    if (id) {
        getblogss(id).then(data=>{
            console.log(data);
            $('#id').val(data[0].id)
            $('[name=bt]').val(data[0].title)
            $('[name=zy]').val(data[0].digest)
            $('[name=nr]').val(data[0].content)
            $('[name=fl]').val(data[0].class)
            $('[name=zz]').val(data[0].author)
           })
    }
})

function query() {
    let keyword = $('[name=keyword]').val()
    getblogs(keyword).then(data => {
        rendata(data)
    })
}
function rendata(res) {
    let tr = $('.tr')
    tr.remove()
    res.forEach(item => {
        let html = `
        <tr class="tr" key="${item.id}">
            <td>${item.id}</td>
            <td>${item.title}</td>
            <td>${item.digest}</td>
            <td>${item.content}</td>
            <td>${item.class}</td>
            <td>${item.author}</td>
            <td>${item.time}</td>
            <td>
                <input type="button" name="" id="" value="修改" onclick="edit(${item.id})">
                <input type="button" name="" id="" value="删除" onclick="del(${item.id})">

            </td>
        </tr>
        `
        $('#tb').append(html)
    });
}
function add() {
    location.href = './addOrEdit.html'
}
function cencel() {
    location.href = './index.html'

}
function save() {
    let id = $('#id').val()
    let title = $('[name=bt]').val()
    let digest = $('[name=zy]').val()
    let content = $('[name=nr]').val()
    let classs = $('[name=fl]').val()
    let author = $('[name=zz]').val()
    let obj = {
        id,
        title,
        digest,
        content,
        classs,
        author
    }
    console.log(obj);
    if (obj.id) {
        putblogs(obj,obj.id).then(data=>{
            if (data.code === 1000) {
                location.href = './index.html'
            } else {
                alert('出错了')
            }
        })
    } else {
        postblogs(obj).then(data => {
            if (data.code === 1000) {
                location.href = './index.html'
            } else {
                alert('出错了')
            }
        })
    }

}
function del(id) {
    if (confirm(`确认删除id为${id}这个的博客吗？`)) {
        delblogs(id).then(data => {
            let id = data.data.id
            $(`[key=${id}]`).remove()
        })
    }
}
function edit(id) {
    location.href = `./addOrEdit.html?${id}`
}